<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\admin\model\Customer as CustomerModel;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 客户管理
 *
 * @icon fa fa-users
 */
class Customer extends Backend
{
    /**
     * 客户模型对象
     * @var \app\admin\model\Customer
     */
    protected $model = null;
    
    /**
     * 初始化方法
     */
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new CustomerModel();
    }
    
    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            
            // 获取查询参数
            $filter = $this->request->get("filter", '');
            $filter = (array)json_decode($filter, true);
            $op = $this->request->get("op", '', 'trim');
            $op = (array)json_decode($op, true);
            
            // 组装查询条件
            $where = [];
            $searchFields = ['name', 'contact', 'store_name', 'tags'];
            
            foreach ($searchFields as $field) {
                if (isset($filter[$field]) && $filter[$field] !== '' && isset($op[$field])) {
                    $operator = $op[$field] === 'like' ? 'LIKE' : $op[$field];
                    $value = $op[$field] === 'like' ? '%'.$filter[$field].'%' : $filter[$field];
                    $where[$field] = [$operator, $value];
                }
            }
            
            // 查询状态筛选
            if (isset($filter['status']) && $filter['status'] !== '') {
                $where['status'] = $filter['status'];
            }
            
            // 查询数据
            $list = $this->model
                ->where($where)
                ->order('id', 'desc')
                ->paginate($this->request->request('limit', 10));
            
            $result = ['total' => $list->total(), 'rows' => $list->items()];
            return json($result);
        }
        
        return $this->view->fetch();
    }
    
    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                
                $result = false;
                Db::startTrans();
                try {
                    // 验证
                    $validate = validate('Customer');
                    $validate->scene('add')->check($params);
                    
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        
        return $this->view->fetch();
    }
    
    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                
                $result = false;
                Db::startTrans();
                try {
                    // 验证
                    $validate = validate('Customer');
                    $validate->scene('edit')->check($params);
                    
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
    
    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        
        // 检查是否存在关联销售单
        $saleOrderCount = \think\Db::name('sale_order')->where('customer_id', 'in', $ids)->count();
        if ($saleOrderCount > 0) {
            $this->error(__('删除失败，该客户有关联的销售单数据'));
        }
        
        // 检查是否存在关联账单
        $billCount = \think\Db::name('customer_bill')->where('customer_id', 'in', $ids)->count();
        if ($billCount > 0) {
            $this->error(__('删除失败，该客户有关联的账单数据'));
        }
        
        $list = $this->model->where($pk, 'in', $ids)->select();
        
        $count = 0;
        Db::startTrans();
        try {
            foreach ($list as $k => $v) {
                $count += $v->delete();
            }
            Db::commit();
        } catch (PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        
        if ($count) {
            $this->success();
        } else {
            $this->error(__('No rows were deleted'));
        }
    }
    
    /**
     * 批量更新
     */
    public function multi($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        
        $params = $this->request->post("params");
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', 'params'));
        }
        parse_str($params, $paramsArr);
        
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        
        $count = 0;
        Db::startTrans();
        try {
            $count = $this->model->where('id', 'in', $ids)->update($paramsArr);
            Db::commit();
        } catch (PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        
        if ($count) {
            $this->success();
        } else {
            $this->error(__('No rows were updated'));
        }
    }
} 